<script lang="ts">
import { useAntdForm } from '@peng_kai/kit/antd';
import { InputOtp, InputPassword } from '~/components/input';
import { flzxsqc } from '~/utils';

export const verify2FAPopup = useAntdModal(
  // eslint-disable-next-line import/no-self-import
  defineAsyncComponent(() => import('./Verify2FA.vue')),
  {
    title: computed(() => $t('cVPpgXIbaG2hoOvOn9Syf')),
    wrapClassName: 'ant-cover__Modal',
    width: 400,
    centered: true,
    maskClosable: false,
    footer: null,
    rejectOnClose: true,
  },
);
</script>

<script setup lang="ts">
const props = defineProps<{
  requirePassword?: boolean;
}>();
const emits = defineEmits<{
  confirm: [{ password: string; security_code: string }];
  close: [];
}>();

const form = useAntdForm({
  security_code: {
    value: '',
    rules: [
      { required: true, type: 'string', len: 6, message: $t('9QtWqL7hc0fzViFGn0Es') },
    ],
  },
  password: {
    value: '',
    rules: [{ required: true, type: 'string', message: $t('mfFbQx6d5lMlEhlQg5eV') }],
  },
});
const disabled = computed(() => false);
async function confirm() {
  const state = await form.$form.validate?.().catch(() => {});

  if (state) {
    state.password = state.password ? flzxsqc(state.password) : state.password;
    emits('confirm', state as any);
    emits('close');
  }
}
</script>

<template>
  <div
    class="h-90 rounded-t-4 bg-sys-layer-d"
    bodyClass="text-base text-sm text-sys-text-body max-h-75vh overflow-y-auto"
    @close="emits('close');"
  >
    <AForm v-bind="form.props" class="ant-cover__Form-compact" hideRequiredMark :disabled="disabled" layout="vertical" @finish="confirm()">
      <AFormItem v-bind="form.itemProps.security_code" :label="$t('vrOaTrsSDoDwKhZqxWG')">
        <InputOtp v-model:value="form.state.security_code" autoFocus />
      </AFormItem>
      <AFormItem v-if="props.requirePassword" v-bind="form.itemProps.password" :label="$t('ph7eJFfBmsn7xFyvj8')">
        <InputPassword v-model:value="form.state.password" :placeholder="$t('sbNd6Np6qPuRup0ZhZbYz')" />
      </AFormItem>
      <AButton
        class="ant-cover__Button-3d-primary mt-4" type="primary" htmlType="submit" block
        :disabled="disabled" :loading="disabled"
      >
        {{ $t('fVhxPoy2u9I4Q6dqrMh') }}
      </AButton>
    </AForm>
  </div>
</template>
